﻿using Basic.WxApiRemoteModel.WxFilter.Model;
using Basic.WxCollect;
using Basic.WxModel.DB;
using Basic.WxModel.WxFilter;
using Basic.WxModel.WxMsgFilter;
using Basic.WxService.Interface;
using WeDonekRpc.Helper;
using WeDonekRpc.Model;

namespace Basic.WxService.lmpl
{
    internal class WxFilterService : IWxFilterService
    {
        private readonly IWxFilterCollect _Filter;
        private readonly IWxMsgFilterCollect _MsgFilter;

        public WxFilterService (IWxFilterCollect filter, IWxMsgFilterCollect msgFilter)
        {
            this._Filter = filter;
            this._MsgFilter = msgFilter;
        }

        public void Sync (WxFilterDto[] filters, MsgSource source)
        {
            long id = this._Filter.FindId(source.RpcMerId, source.SystemType);
            if (id == 0)
            {
                this._Filter.Add(new WxFilterAdd
                {
                    SystemType = source.SystemType,
                    RpcMerId = source.RpcMerId,
                    Adds = filters
                });
                return;
            }
            DBWxMsgSubscribeFilter[] datas = this._MsgFilter.GetsBySubscribeId(id);
            WxMsgFilterSet set = new WxMsgFilterSet
            {
                SubscribeId = id,
                Adds = filters.FindAll(c => !datas.IsExists(a => c.WxAppId == a.WxAppId && c.AppId == a.WxAppId && a.FilterType == c.FilterType && a.MsgType == c.MsgType)),
                Update = [],
                DeleteId = datas.Convert(c => !filters.IsExists(a => c.WxAppId == a.WxAppId && c.AppId == a.WxAppId && a.FilterType == c.FilterType && a.MsgType == c.MsgType), c => c.Id)
            };
            filters.ForEach(c =>
            {
                DBWxMsgSubscribeFilter sour = datas.Find(a => c.WxAppId == a.WxAppId && c.AppId == a.WxAppId && a.FilterType == c.FilterType && a.MsgType == c.MsgType);
                if (sour != null)
                {
                    set.Update.Add(new FilterSet
                    {
                        Direct = c.Direct,
                        ForwardType = c.ForwardType,
                        Id = sour.Id,
                        Reply = c.Reply
                    });
                }
            });
            this._MsgFilter.Set(set);
        }
    }
}
